import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

const MIME_MAP = {
  '.mp4': 'video/mp4',
  '.webm': 'video/webm',
  '.ogg': 'video/ogg',
  '.mov': 'video/quicktime',
  '.avi': 'video/x-msvideo',
  '.mkv': 'video/x-matroska',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.png': 'image/png',
  '.gif': 'image/gif',
  '.webp': 'image/webp',
  '.svg': 'image/svg+xml'
};

export async function GET(req, {params}) {
  const { filename } = await params;
  const filePath = path.join(process.cwd(), 'uploads', filename);
  if (!fs.existsSync(filePath)) { return new NextResponse('Not found', { status: 404 }); }
  const ext = path.extname(filename).toLowerCase();
  const mime = MIME_MAP[ext] || 'application/octet-stream';
  const stat = fs.statSync(filePath);

  const range = req.headers.get('range');
  if (range && /^bytes=/.test(range)) {
    const [startStr, endStr] = range.replace(/bytes=/, '').split('-');
    const start = parseInt(startStr, 10);
    const end = endStr ? parseInt(endStr, 10) : stat.size - 1;
    const chunkSize = end - start + 1;
    const file = fs.createReadStream(filePath, { start, end });
    return new NextResponse(file, {
      status: 206,
      headers: {
        'Content-Range': `bytes ${start}-${end}/${stat.size}`,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunkSize,
        'Content-Type': mime,
        'Cache-Control': 'public, max-age=31536000'
      }
    });
  }

  const file = fs.createReadStream(filePath);
  return new NextResponse(file, {
    status: 200,
    headers: {
      'Content-Type': mime,
      'Content-Length': stat.size,
      'Cache-Control': 'public, max-age=31536000',
      'Content-Disposition': 'inline'
    }
  });
}